#include "DefaultItemDelegate.h"

#include <core/StyleMgr.h>

#include <QJsonArray>
#include <QJsonValue>
#include <QPainter>

#include "../KeySearchWidget.h"

// #include <QJsonDocument>
// #include <QFile>
// #include <QDebug>

DefaultItemDelegate::DefaultItemDelegate(KeySearchWidget* parent,
                                         int itemHeight, int fontSize)
    : QStyledItemDelegate(parent),
      m_itemHeight(itemHeight),
      m_fontSize(fontSize) {}

void DefaultItemDelegate::paint(QPainter* painter,
                                const QStyleOptionViewItem& option,
                                const QModelIndex& index) const {
  QVariant var = index.data(Qt::UserRole);
  QJsonArray data = var.toJsonArray();

  QString str0 = data[0].toString();
  QStringList strList = str0.split('|');
  QRect rect = option.rect;

  // TODO: Tricky, 不设置listwidget的stylesheet，这里的MouseOver就不正常！
  if (option.state & QStyle::State_MouseOver &&
      index.flags() != Qt::ItemFlag::NoItemFlags) {
    if (strList.size() > 0 && strList[0] == "title") {
    } else {
      painter->fillRect(rect, StyleMgr::instance().color("Hover"));
    }
  }

  QFont font = option.font;
  font.setPointSize(m_fontSize);
  painter->setFont(font);

  QPen pen(StyleMgr::instance().color("TextNormal"));
  if (option.state.testFlag(QStyle::StateFlag::State_Selected))
    pen.setColor(StyleMgr::instance().color("Highlight"));

  painter->setPen(pen);

  if (strList.size() > 0 && strList[0] == "title" && data.size() > 1) {
    rect.setWidth(option.rect.width());
    painter->fillRect(rect, StyleMgr::instance().color("ContactBlack"));
    painter->drawText(rect, Qt::AlignLeft | Qt::AlignVCenter,
                      data[1].toString());
  } else {
    for (int i = 1; i < data.size(); ++i) {
      if (i > m_widths.size()) break;

      if (strList.size() > 0 && strList[0] == "data" &&
          strList[1] == "issuer") {
        rect.setWidth(option.rect.width());
      } else {
        rect.setWidth(m_widths[i - 1]);
      }

      if (data[i].toString() == tr("模块") ||
          data[i].toString() == tr("债券")) {
        pen.setColor(QColor(0xFABF55));
        painter->setPen(pen);
      }

      painter->drawText(rect.adjusted(i == 1 ? 4 : 0, 0, -5, 0),
                        Qt::AlignLeft | Qt::AlignVCenter, data[i].toString());
      rect.moveTo(rect.topRight());
      if (rect.left() > option.rect.right()) break;
    }
  }
}

QSize DefaultItemDelegate::sizeHint(const QStyleOptionViewItem& option,
                                    const QModelIndex& index) const {
  return QSize(250, m_itemHeight);
}
